<template>
    <div class="flex mt-lg">
        <div class="head-box  text-center pointer" @click="upload">
            <img v-if="avatarImg" :src="avatarImg">
            <template v-else>
                <i class="el-icon-plus f-s-26 mt-lg"></i>
                <p class="txt">{{ $t('global.uploadImg')}} </p>
            </template>
        </div>
        <div class="ml-lg mt-lg">
            <el-button type="primary" @click="upload">{{ $t('global.upload') }}</el-button>
            <div class="f-s-12 colorb2b"> {{ $t('global.typeWarn',{0: '.jpg|.png'})}}</div>
        </div>
    </div>
</template>

<script>
import {
    uploadFile
} from '@/utils/uploadFile'
export default {
    data () {
        return {
            avatarImg: ''
        }
    },
    props: ['dataAvatar'],
    watch: {
        dataAvatar (nVal, oVal) {
            this.avatarImg = this.dataAvatar ? this.dataAvatar : ''
        }
    },
    mounted () {
        this.avatarImg = this.dataAvatar ? this.dataAvatar : ''
    },
    methods: {
        // 上传头像部分
        picToBase64 (file, fn) {
            let reader = new FileReader()
            reader.addEventListener('load', e => {
                fn(e)
            })
            reader.readAsDataURL(file)
        },
        upload () {
            uploadFile({
                accept: '.jpg,.png'
            })
                .then(file => {
                    if (!/(\.jpg|\.png)$/.test(file.name.toLowerCase())) {
                        this.$message({
                            type: 'warning',
                            message: this.$t('global.typeWarn', {
                                0: '.jpg|.png'
                            })
                        })
                        return false;
                    }

                    let formData = new FormData()
                    formData.append('uploadFile', file)
                    this.$post({
                        url: '/upload',
                        data: formData
                    })
                        .then(res => {
                            this.picToBase64(file, e => {
                                this.avatarImg = e.target.result
                            })
                            this.$emit('getMethod', res.path)
                        })
                })
        },
    }
}
</script>

<style scoped lang="scss">
.head-box {
    overflow: hidden;
    height: 100px;
    width: 100px;
    background-color: #fff;
    border: 1px dashed #b2b2b2;
    color: #7f7f7f;

    img {
        width: auto;
        max-width: 100px;
        height: 100px;
        vertical-align: bottom;
    }

    .txt {
        line-height: 14px;
    }
}
</style>
